<?php
declare (strict_types = 1);

namespace app;

use think\App;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Log;
use think\Response;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 请求id
     * @var string 
     */
    protected $requestID;

    /**
     * 服务层
     * @var 
     */
    protected $dataService;

    /**
     * 请求数据
     * @var
     */
    protected $dataRequest;

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        $this->requestID = strtoupper(uniqid(date('ymdHis') . create_random_string(2), true));

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {

    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    /**
     * 返回成功
     * User Reborn
     * Time 2020/3/30 16:25
     * @param $data
     * @param string $message
     * @param array $header
     * @return Response
     */
    protected function ajaxSuccess($data, $message = '', array $header = []): Response
    {
        $result = [
            'status' => 1,
            'now' => time(),
            'code' => '000000',
            'info' => (string)$message,
            'data' => $data,
            'req_id' => $this->requestID,
        ];
        $this->writeRequestLog($result);
        $type = $this->request->param('callback') ? 'jsonp' : 'json';
        $response=Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 返回失败
     * User Reborn
     * Time 2020/3/30 16:25
     * @param $code
     * @param string $message
     * @param array $header
     * @return Response
     */
    protected function ajaxError($message='',$code=500, array $header = []): Response
    {
        $result = [
            'status' => 0,
            'now' => time(),
            'code' => (string)$code,
            'info'  => (string)$message,
            'data' => '',
            'req_id' => $this->requestID,
        ];
        $this->writeRequestLog($result);
        $type = $this->request->param('callback') ? 'jsonp' : 'json';
        $response=Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 记录响应的日志
     * @param $result
     */
    protected function writeRequestLog($result)
    {
        $log = date('Y-m-d H:i:s') . '  ' . $this->requestID . "  \r\n";
        $log .= 'return:' . \json_encode($result, JSON_UNESCAPED_UNICODE) . "\r\n\r\n";
        Log::write($log);
    }

    /**
     * 首页列表
     * User Reborn
     * Time 2020/4/10 18:56
     */
    public function index()
    {
        $param=$this->dataRequest->requestData($this->request->param(),'index');
        $where[]=['id','=',$param['id']];
        $data=$this->dataService->paginate($param,$where);
        $this->ajaxSuccess($data);
    }

    /**
     * 新增
     * User Reborn
     * Time 2020/4/10 18:56
     */
    public function save()
    {
        $param=$this->dataRequest->requestData($this->request->param(),'data');
        if(!$this->service->add($param)){
            $this->ajaxError('操作失败');
        }
        $this->ajaxSuccess('');
    }

    /**
     * 更新
     * User Reborn
     * Time 2020/4/10 18:56
     * @param $id
     */
    public function edit($id)
    {
        $param=$this->dataRequest->requestData($this->request->param(),'data');
        if(!$this->service->renew($id,$param)){
            $this->ajaxError('操作失败');
        }
        $this->ajaxSuccess('');
    }

    /**
     * 删除
     * User Reborn
     * Time 2020/4/10 18:56
     * @param $id
     */
    public function delete($id)
    {
        if ($this->service->remove($id) === false) {
            $this->ajaxError('操作失败');
        }

        $this->ajaxSuccess('');
    }
}
